package com.eric.springboot.controller;

import com.eric.springboot.common.CommonResult;
import com.eric.springboot.common.RedisCacheConstants;
import com.eric.springboot.config.redis.service.RedisService;
import com.eric.springboot.entity.UserLoginRequest;
import com.eric.springboot.service.UserService;
import com.eric.springboot.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Eric
 * @date 2021.2.3
 * 认证处理器
 */
@RestController
@RequestMapping("/auth")
@Api(tags = "认证")
public class AuthController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    /**
     * 登陆
     *
     * @param userLoginRequest 用户登陆实体
     * @return
     */
    @ApiOperation("登陆")
    @PostMapping("/login")
    public CommonResult login(@RequestBody UserLoginRequest userLoginRequest) {
        String token = userService.login(userLoginRequest);
        Map<String, String> tokenMap = new HashMap<>(2);
        tokenMap.put("token", token);
        return CommonResult.success(tokenMap);
    }

    /**
     * 注册
     *
     * @param userLoginRequest 用户注册实体
     * @return
     */
    @ApiOperation("注册")
    @PostMapping("/register")
    public CommonResult register(@RequestBody UserLoginRequest userLoginRequest) {
        userService.register(userLoginRequest);
        return CommonResult.success(null);
    }

    /**
     * 登陆
     *
     * @return
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public CommonResult logout() {
        redisService.del(RedisCacheConstants.TOKEN_KEY + SecurityUtils.getCurrentUserId());
        return CommonResult.success(null);
    }
}
